﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Threading;
using System.Collections.ObjectModel;

// Toolkit namespace
using System.Windows.Input;
using System.Windows.Media;
using SimpleMvvmToolkit;
using System.Linq;
// Toolkit extension methods
using SimpleMvvmToolkit.ModelExtensions;
using SpotTheMisspell.Models;

namespace SpotTheMisspell
{
    /// <summary>
    /// This class contains properties that a View can data bind to.
    /// <para>
    /// Use the <strong>mvvmprop</strong> snippet to add bindable properties to this ViewModel.
    /// </para>
    /// </summary>
    public class MainPageViewModel : ViewModelBase<MainPageViewModel>
    {
        
        // Default ctor
        public MainPageViewModel()
        {
            RegisterToReceiveMessages<ParagraphDesriber,bool>(MessageToken.StartGame,LoadGame);
           
        }
        
        void LoadGame(object sender, NotificationEventArgs
      <ParagraphDesriber, bool> e)
        {

            WordCollection = new ObservableCollection<Word>();
            CurrentParagraph = ParagraphFactory.createParagraph(e.Data.Misspelled, e.Data.Word);

            foreach (var val in CurrentParagraph.WordsContent)
            {
                WordCollection.Add(val);
            }

            NumberOfSelectedWord = 0;

            
            pageTitle = CurrentParagraph.TimeToGuess.TotalSeconds.ToString();
            dt = new System.Windows.Threading.DispatcherTimer();
            dt.Interval = new TimeSpan(0, 0, 0, 1,20); // 1 Seconds
            dt.Tick += new EventHandler(dt_Tick);
            _counter = (CurrentParagraph.TimeToGuess.TotalSeconds);
        }
        public void startGame()
        {
            //start timer
            dt.Start();
        }
        void dt_Tick(object sender, EventArgs e)
        {
            _counter--;
            if (_counter > -1)
            {
                PageTitle = _counter.ToString();
            }
            else
            {
                NotifyError("Time's Up!",null);
                dt.Stop();
            }
        }

        private double _counter =0;
        private System.Windows.Threading.DispatcherTimer dt;

        public int GameTime  { get; set; }

        // Add events to notify the view or obtain data from the view
        public event EventHandler<NotificationEventArgs<Exception>> ErrorNotice;

     
        
        private Paragraph CurrentParagraph;
        private int NumberOfSelectedWord;

        public string TotalMisspellString
        {
            get
            {
                if (CurrentParagraph == null)
                    return "";
                
               return "Number of Misspell Word :" + CurrentParagraph.TotalMisspell;
             }
            set
            {
                NotifyPropertyChanged(m => m.TotalMisspellString);
            }
        }
        public string TotalSelectedString
        {
            get { return "Number of Selected Word " + NumberOfSelectedWord; }
            set
            {
                NotifyPropertyChanged(m => m.TotalSelectedString);
            }
        }

        // Add Header property using the mvvmprop code snippet
        private string pageTitle = "00";
        public string PageTitle
        {
            get
            {
                if (IsInDesignMode) return "page title";
                return pageTitle;
            }
            set
            {
                pageTitle = value;
                NotifyPropertyChanged(m => m.PageTitle);
            }
        }
        private ObservableCollection<Word> _wordCollection;
        public ObservableCollection<Word> WordCollection
        {
            get { return _wordCollection; }
            set
            {
                _wordCollection = value;
                NotifyPropertyChanged(m => m.WordCollection);
            }
        }
        public ICommand Hore
        {
            get { return new DelegateCommand<int>((val)=>
                                                      {
                                                          var temp = WordCollection[val];
                                                          if (NumberOfSelectedWord < CurrentParagraph.TotalMisspell )
                                                          {
                                                              if (!temp.IsSelected)
                                                              {
                                                                  NumberOfSelectedWord++;
                                                              }
                                                              else
                                                              {
                                                                  NumberOfSelectedWord--;
                                                              }
                                                              WordCollection[val] = temp;
                                                              NotifyPropertyChanged(m => m.TotalSelectedString);
                                                              temp.IsSelected = !temp.IsSelected;
                                                          }else if (temp.IsSelected)
                                                          {
                                                              NumberOfSelectedWord--;
                                                              WordCollection[val] = temp;
                                                              NotifyPropertyChanged(m => m.TotalSelectedString);
                                                              temp.IsSelected = !temp.IsSelected;
                                                          }

                                                          })
                ;
            }
        }

  
            
        // Helper method to notify View of an error
        private void NotifyError(string message, Exception error)
        {
            // Notify view of an error
            Notify(ErrorNotice, new NotificationEventArgs<Exception>(message, error));
            App.Navigator.Navigate("ResultPage");
            
            //send the data
            List<Word> misspelled = new List<Word>();
            foreach (var word in WordCollection)
            {
                if (word.IsMisspell )
                {
                    misspelled.Add(word);
                }

            }
            // order based on selection
            misspelled = misspelled.OrderBy(b => b.IsSelected).ToList();
            SendMessage(MessageToken.GuessedWordList,new NotificationEventArgs<List<Word>,bool>(null,misspelled,onResultShowInvoked));
        }
        void onResultShowInvoked(bool res)
        {
        }

    }
}